  <template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产品类型">
              <el-select v-model="searchForm.deviceTypeId" filterable placeholder="请选择产品类型">
                <el-option v-for="item in deviceTypeDic" :key="item.deviceTypeId"
                  :label="item.deviceTypeName + ' ' + item.deviceClassify + ' ' + item.deviceTypeCode"
                  :value="item.deviceTypeId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="产品序列号">
              <el-input v-model="searchForm.deviceCode" placeholder="产品序列号" clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <div>
          <el-button type="primary" size="small" @click="toDeviceType">产品类型管理</el-button>
          <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
          <el-button type="primary" size="small" @click="batchCreate">批量上传</el-button>
        </div>

        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>

      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
        <el-table-column label="产品名称" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeDto.deviceTypeName }}
          </template>
        </el-table-column>

        <el-table-column label="产品型号" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeDto.deviceTypeCode }}
          </template>
        </el-table-column>

        <el-table-column label="产品序列号" align="center">
          <template #default="{ row }">
            {{ row.deviceCode }}
          </template>
        </el-table-column>

        <el-table-column label="买方" align="center">
          <template #default="{ row }">
            {{ row.supplierName }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
            <el-popconfirm title="是否要删除该产品？" confirmButtonText="确认" cancelButtonText="取消"
              @confirm="handleDelete(scope.row.deviceId)">
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
          :page-size="limit" @current-change="initTableData" />
      </div>

      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">

        <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">

          <el-form-item label="产品类型" prop="deviceTypeId">
            <el-select v-model="form.deviceTypeId" filterable placeholder="请选择产品类型">
              <el-option v-for="item in deviceTypeDic" :key="item.deviceTypeId"
                :label="item.deviceTypeName + ' ' + item.deviceClassify + ' ' + item.deviceTypeCode"
                :value="item.deviceTypeId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产品序列号" prop="deviceCode">
            <el-input v-model="form.deviceCode" placeholder="产品序列号"></el-input>
          </el-form-item>

          <el-form-item label="产品状态" prop="deviceStatus">
            <el-select v-model="form.deviceStatus" filterable placeholder="请选择产品状态">
              <el-option v-for="item in deviceStatusDic" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="买方">
            <el-button @click="dialogTableVisible_company = true" >
              {{ checkedCompany == null ? '选择分销商' : checkedCompany.name }}
            </el-button>
            <!-- <el-button type="primary" size="small" text v-if="editId != 0" @click="cleanCustomer">置空供货商</el-button> -->
          </el-form-item>

          <el-form-item label="合同签订日期">
            <el-date-picker v-model="form.contractSignDate" type="date" placeholder="合同签订日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="质保条款">
            <el-input type="textarea" :rows="2" v-model="form.warrantyTerms" placeholder="质保条款"></el-input>
          </el-form-item>

          <el-form-item label="发货日期">
            <el-date-picker v-model="form.deliveryDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="完工日期">
            <el-date-picker v-model="form.completionDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="交船日期">
            <el-date-picker v-model="form.shipDeliveryDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="质保截至日期">
            <el-date-picker v-model="form.warrantyEndDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="历史维修记录">
            <el-input type="textarea" :rows="4" v-model="form.remarks" placeholder="历史维修记录"></el-input>
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>

    <el-dialog v-model="batchformDrawer" title="批量产品入库"  align-center>
      <el-form :model="ruleForm" label-width="120px" :inline="false">
          <el-form-item label="模板下载：">
            <el-link type="primary" :underline="false"  @click="downloadTemplate" >批量产品上传模板下载</el-link>
          </el-form-item>
          <!-- 添加文件上传组件 -->
          <el-form-item label="上传附件：" prop="files">
            <el-upload class="hide"
              action="" 
              accept=".xlsx,.xls"
              :multiple="false"
              :on-change="handleChange"
              :file-list="ruleForm.fileList"
              :http-request="handleUpload"
              :auto-upload="true">
            <el-button slot="trigger" type="primary" plain>上传文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" style="width: 35%">开始导入</el-button>
        </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 选择公司弹窗 -->
    <!-- <el-dialog v-model="dialogTableVisible_company" title="选择供货商" width="70%" align-center>
      <SelectCompany v-if="dialogTableVisible_company" :selectedCompanyId="form.supplierId"
        @getCheckedCompany="getCheckedCompany" :showSelection="true" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible_company = false">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog> -->

    <!-- 选取供货商dialog -->
    <SystemDialog title="选择供货商" :visible="dialogTableVisible_company" :height="60" :width="70"
      @on-close="dialogTableVisible_company = false" @on-confirm="dialogTableVisible_company = false">
      <template v-slot:content>
        <SelectCompany v-if="dialogTableVisible_company" :selectedCompanyId="form.supplierId" 
          @getCheckedCompany="getCheckedCompany" :showSelection="true"/>
      </template>
    </SystemDialog>
  </template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import { toast, toastWarn } from "~/composables/util"
import { useRouter } from 'vue-router'
import SystemDialog from "~/components/SystemDialog.vue";
import SelectCompany from "~/components/select-company.vue";
import { getDeviceList, addDevice, updateDevice, deleteDevice, getDeviceTypeList, updateDeviceFile ,deviceBatchCreate} from "~/api/supply"


// 产品状态字典数据 0保内 1保外 
const deviceStatusDic = ref([{ "key": 0, "value": "保内" }, { "key": 1, "value": "保外" }])

// 路由
const router = useRouter()

//产品类型字典数据
const deviceTypeDic = ref([])

//选择公司弹窗
const dialogTableVisible_company = ref(false)
const checkedCompany = ref(null)

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableData = ref([])
const loading = ref(false)

// 查询条件
const searchForm = reactive({
  deviceCode: "",
  deviceTypeId: null,
  page: currentPage.value,
  size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
  searchForm.deviceCode = ""
  searchForm.deviceTypeId = null
  initTableData(1)
}

// 生命周期函数
onMounted(() => {

  //初始化产品类型
  initDeviceType()

  //初始化列表数据
  initTableData()
})

//初始化产品类型
function initDeviceType() {
  //查询全部
  let paramIo = {
    page: 1,
    size: 100,
  }
  getDeviceTypeList(paramIo)
    .then(res => {
      if (res) {
        deviceTypeDic.value = res.records
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取数据
function initTableData(p = null) {
  //指定页码是否为空
  if (typeof p == "number") {
    currentPage.value = p
  }

  loading.value = true
  searchForm.page = currentPage.value

  getDeviceList(searchForm)
    .then(res => {
      if (res) {
        tableData.value = res.records
        total.value = res.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 删除
const handleDelete = (id) => {
  loading.value = true
  deleteDevice(id).then(res => {
    toast("删除成功")
    initTableData()
  })
    .finally(() => {
      loading.value = false
    })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
  //产品类型
  deviceTypeId: null,
  //产品序列号
  deviceCode: null,
  //产品状态
  deviceStatus: null,
  //供货商
  supplierId: null,
  //合同签订日期
  contractSignDate: null,
  //质保条款
  warrantyTerms: null,
  //发货日期
  deliveryDate: null,
  //完工日期
  completionDate: null,
  //交船日期
  shipDeliveryDate: null,
  //质保截至日期
  warrantyEndDate: null,
  //产品历史维修记录
  remarks: null
})
// 新增按钮点击事件
const handleCreate = () => {
  //修改标记置为0
  editId.value = 0
  //将公司信息清空
  checkedCompany.value = null
  resetForm({
    //产品类型
    deviceTypeId: null,
    //产品序列号
    deviceCode: null,
    //产品状态
    deviceStatus: null,
    //供货商
    supplierId: null,
    //合同签订日期
    contractSignDate: null,
    //质保条款
    warrantyTerms: null,
    //发货日期
    deliveryDate: null,
    //完工日期
    completionDate: null,
    //交船日期
    shipDeliveryDate: null,
    //质保截至日期
    warrantyEndDate: null,
    //产品历史维修记录
    remarks: null
  })
  //打开弹窗
  formDrawerRef.value.open()
}

//执行表单校验
const rules = {
  deviceTypeId: [
    { required: true, message: '产品类型不能为空', trigger: 'change' }
  ],
  deviceCode: [
    { required: true, message: '产品序列号不能为空', trigger: 'change' }
  ],
}
//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
//提交表单
const handleSubmit = () => {
  //表单校验
  formRef.value.validate((valid) => {
    if (!valid) return
    //console.log(JSON.stringify(form))
    formDrawerRef.value.showLoading()
    //根据是否是修改标记，判断执行新增接口还是修改接口
    const fun = editId.value ? updateDevice(editId.value, form) : addDevice(form)
    fun.then(res => {
      toast(drawerTitle.value + "成功")
      // 修改刷新当前页，新增刷新第一页
      initTableData(editId.value ? false : 1)
      formDrawerRef.value.close()
    }).finally(() => {
      //close loading
      formDrawerRef.value.hideLoading()
    })
  })
}
// 重置表单
function resetForm(row = false) {
  if (formRef.value) formRef.value.resetFields()
  if (row) {
    for (const key in form) {
      form[key] = row[key]
    }
  }
}
// 跳转至toDeviceType
const toDeviceType = () => {
  router.push("/deviceType")
}
// 编辑
const handleEdit = (row) => {
  editId.value = row.deviceId
  //给公司信息赋值回显-供货商
  if (null == row.supplierId) {
    checkedCompany.value = null
  } else {
    checkedCompany.value = { id: row.supplierId, name: row.supplierName }
  }
  resetForm(row)

  //产品类型
  form.deviceTypeId = row.deviceTypeDto.deviceTypeId
  formDrawerRef.value.open()
}

const filesInfo = ref([])
const ruleForm = reactive({
  fileList: [],
})
const batchformDrawer = ref(false)
// 批量上传按钮点击事件
const batchCreate = () => {
  //修改标记置为0
  editId.value = 0
  ruleForm.fileList = [];
  filesInfo.value = [];
  //打开弹窗
  batchformDrawer.value = true
}


//文件状态改变
const handleChange = (file, fileList) => {
    form.files = fileList;
}

//上传文件
const handleUpload = (param) => {
    const File = param.file;
    let paramIo = new FormData();
    paramIo.append("file", File);
    updateDeviceFile(paramIo).then((res) => {
      filesInfo.value = res;
      toast("上传成功")
    });
} 

// 批量导入
const onSubmit = () => {
  if(filesInfo.value.length > 0){
    console.log('第一条附件的信息:',filesInfo.value[0].url);
    const url = filesInfo.value[0].url;
    const fileName = url.substring(url.lastIndexOf("/")+1,url.length);
    let paramIo = new FormData();
    paramIo.append("fileName", fileName);
    deviceBatchCreate(paramIo).then(res => {
      toast("文件处理成功");
      // 关闭弹窗
      batchformDrawer.value = false;

    })
    // deviceBatchCreate(paramIo).then(res => {
    //   return new Promise((resolve, reject) => {
    //     setTimeout(() => {
    //       resolve(toast("文件处理成功"));
    //       batchformDrawer.value = false;
    //     }, 1000);
    //   });
    // })
  }else{
    toastWarn("请选择文件");
  }
}

const downloadTemplate = () => {
  window.location.href = "batchCreateTemplate.xlsx"

};

//获取选择的公司
function getCheckedCompany(data) {
  // console.log('checked customer: ', JSON.stringify(data))
  if (data != null) {
    form.supplierId = data.id
    checkedCompany.value = data
  }
}

//清除已选择的公司
function cleanCustomer() {
  form.supplierId = null
  checkedCompany.value = null
}

//格式化产品类型
// function formatDeviceType(deviceTypeId) {
//   let item = deviceTypeDic.value?.find(x => x.deviceTypeId == deviceTypeId)
//   return item.deviceTypeName+' '+item.deviceClassify+' '+item.deviceTypeCode
// }
</script>

<style scoped>
.hide ::v-deep .el-upload-list__item .el-icon--close{
  display: none !important;
}
</style>